package com.zyy.client;

import com.zyy.handler.UserClientHandler;
import com.zyy.handler.UserClientInitializer;
import com.zyy.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zyy
 * @date 2021/2/23 下午2:35
 * @description
 */
public class RPCConsumer {

    //1.创建一个线程池对象 -- 它要处理我们的自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;


    //3.编写方法 初始化客户端（创建连接池 bootstrap 设置bootStrap 连接服务器）
    public static void initClient() throws InterruptedException {
        //1)初始化UserClentHandler
        userClientHandler = new UserClientHandler();
        //2)创建连接组对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        //4)设置bootStrap
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听Handler并初始化
                .handler(new UserClientInitializer(userClientHandler));

        //5）连接服务器
        bootstrap.connect("127.0.0.1",8999).sync();
    }
    //4.编写一个方法 使用JDK动态代理创建对象
    public static  Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.初始化客户端Client
                        if(userClientHandler == null){
                            initClient();
                        }
                        //封装
                        RpcRequest rpcRequest = new RpcRequest();
                        String requestId = UUID.randomUUID().toString();
                        System.out.println("requestId = " + requestId);
                        String className = method.getDeclaringClass().getName();
                        String methodName = method.getName();
                        Class<?>[] parameterTypes = method.getParameterTypes();

                        rpcRequest.setRequestId(requestId);
                        rpcRequest.setClassName(className);
                        rpcRequest.setMethodName(methodName);
                        rpcRequest.setParameterTypes(parameterTypes);
                        rpcRequest.setParameters(args);

                        //2.给UserClientHandle，设置Param参数
                        userClientHandler.setParam(rpcRequest);
                        System.out.println("设置参数完成："+ rpcRequest);
                        //3.使用线程池。开启一个线程处理call()写操作，并返回结果
                        Object result = executorService.submit(userClientHandler).get();

                        //4.return 结果
                        return result;
                    }
                });
    }


}
